<!doctype html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Todos</title>
	<link rel="shortcut icon" type="image/x-icon" href="img/logo.svg">
	<link rel="stylesheet" href="css/base.css">
	<link rel="stylesheet" href="css/index.css">
	<link rel="stylesheet" href="lib/nprogress/nprogress.css">
</head>

<body>
	<section class="todoapp">
		<header class="header">
			<h1>todos</h1>
			<div style="text-align: right;">
				<button class="import_btn">Import Data</button>
				<button class="export_btn">Export Data</button>
			</div>
			<input class="new-todo createtaskinput" placeholder="What needs to be done?" autofocus>
		</header>
		<!-- This section should be hidden by default and shown when there are todos -->
		<section class="main">
			<input class="toggle-all" type="checkbox">
			<label for="toggle-all">Mark all as complete</label>
			<ul class="todo-list" id="todoListBox">
				<!-- These are here just to show the structure of the list items -->
				<!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
				<!-- <li class="completed">
					<div class="view">
						<input class="toggle" type="checkbox" checked>
						<label>Taste JavaScript</label>
						<button class="destroy"></button>
					</div>
					<input class="edit" value="Create a TodoMVC template">
				</li>
				<li>
					<div class="view">
						<input class="toggle" type="checkbox">
						<label>Buy a unicorn</label>
						<button class="destroy"></button>
					</div>
					<input class="edit" value="Rule the web">
				</li> -->
			</ul>
		</section>
		<!-- This footer should hidden by default and shown when there are todos -->
		<footer class="footer">
			<!-- This should be `0 items left` by default -->
			<span class="todo-count"><strong>0</strong> item active</span>
			<!-- Remove this if you don't implement routing -->
			<ul class="filters">
				<li>
					<a href="javascript:;" id="allBtn">All</a>
				</li>
				<li>
					<a href="javascript:;" id="activeBtn">Active</a>
				</li>
				<li>
					<a href="javascript:;" id="completedBtn">Completed</a>
				</li>
			</ul>
			<!-- Hidden if no completed items are left ↓ -->
			<button class="clear-completed">Clear completed</button>
		</footer>

	</section>

	<!-- <section id="export_content"></section> -->

	<script src="lib/jquery.min.js"></script>
	<script src="lib/template-web.js"></script>
	<script src="lib/nprogress/nprogress.js"></script>
	<script type="text/html" id="todoList">
		{{each todos todo}}
		<li class="{{ todo.completed ? 'completed' : '' }}">
			<div class="view">
				<input class="toggle" type="checkbox" {{ todo.completed ? 'checked' : '' }} data-label="{{ todo.label }}">
				<label>{{ todo.label }}</label>
				<button class="destroy" data-label="{{ todo.label }}"></button>
			</div>
			<input class="edit" value="" data-label="{{ todo.label }}">
		</li>
		{{/each}}
	</script>
	<script>

		; (() => {
			const qs = (...args) => document.querySelector(...args)
			const getItem = (...args) => localStorage.getItem(...args)
			const setItem = (...args) => localStorage.setItem(...args)

			// const export_content = qs('#export_content')

			qs('.import_btn').addEventListener('click', () => {
				let data = prompt('Paste the data to be imported into the input box:\n\n')
				if (!data) return
				try {
					data = JSON.parse(data)
				} catch (error) {
					return alert('Data rule error. Please use the standard array JSON string.')
				}
				if (!Array.isArray(data)) {
					return alert('Data rule error. Please use the standard array JSON string.')
				}
				const todos = JSON.parse(getItem('todos'))
				todos.push(...data.filter(v => !todos.some(v1 => v1.label === v.label)))
				setItem('todos', JSON.stringify(todos))
				location.reload()
			})

			qs('.export_btn').addEventListener('click', () => {
				const todosStr = getItem('todos')
				const input = document.createElement('input');
				input.setAttribute('readonly', 'readonly'); // Prevent the soft keyboard from popping up on the phone
				input.setAttribute('value', todosStr);
				document.body.appendChild(input);
				// input.setSelectionRange(0, 9999);
				input.select();
				const ok = document.execCommand('copy');
				if (ok) {
					document.body.removeChild(input);
					alert('The following data has been copied to the clipboard:\n\n' + todosStr + '\n\n')
				}
			})
		})()

		$(function () {

			var currentListType = localStorage.getItem('currentListType');
			if (!currentListType) {
				currentListType = 'all';
			}
			$('#' + currentListType + 'Btn').addClass('selected');

			var todos = JSON.parse(localStorage.getItem('todos'));
			if (!todos) {
				localStorage.setItem('todos', '[]');
				todos = [];
			}

			function renderList() {
				NProgress.start();

				setTimeout(function () {
					NProgress.done();
				}, 100);

				var renderTodos = todos;

				if (currentListType === 'active') {
					renderTodos = todos.filter(function (todo) {
						return !todo.completed;
					});
				} else if (currentListType === 'completed') {
					renderTodos = todos.filter(function (todo) {
						return todo.completed;
					});
				}

				var html = template('todoList', { todos: renderTodos });
				$('#todoListBox').html(html);

				$('.todo-count > strong').text(todos.filter(function (todo) {
					return !todo.completed;
				}).length);

				localStorage.setItem('currentListType', currentListType);
				localStorage.setItem('todos', JSON.stringify(todos));
			}
			renderList();

			$('.createtaskinput').keyup(function (event) {
				if (event.keyCode === 13) {
					var val = $.trim($(this).val());
					if (val != '') {
						todos = JSON.parse(localStorage.getItem('todos'));
						var todo = todos.find(function (todo) {
							return todo.label === val;
						});
						if (todo) {
							alert('This task name already exist!');
							return;
						}
						todos.unshift({ label: val, completed: false });
						renderList();
						$(this).val('');
					}
				}
			});

			$('#todoListBox').on('click', '.destroy', function (e) {
				var yn = confirm('Are you sure delete?');
				if (yn) {
					var label = $(this).data('label');
					var index = todos.findIndex(function (todo) {
						return todo.label === label;
					});
					todos.splice(index, 1);
					renderList();
				}
				e.stopPropagation();
			});

			$('#todoListBox').on('click', 'li', function (e) {
				$(this).addClass('editing');
				var $edit = $(this).children('input.edit');
				$edit.val($edit.data('label')).focus();
				e.stopPropagation();
			});

			$('#todoListBox').on('click', '.toggle', function (e) {
				e.stopPropagation();
			});

			$('#todoListBox').on('blur keyup', '.edit', function (e) {
				if (e.type === 'keyup') {
					if (e.keyCode === 13) {
						$(this).blur();
					}
					return;
				}
				var newlabel = $.trim($(this).val());
				if (newlabel === '') {
					alert('Please input task name');
					return;
				}

				var label = $(this).data('label');
				if (newlabel === label) {
					$(this).parent().removeClass('editing');
					return;
				}

				var todo = todos.find(function (todo) {
					return todo.label === newlabel;
				});
				if (todo) {
					alert('This task name already exist!');
					return;
				}

				todo = todos.find(function (todo) {
					return todo.label === label;
				});
				todo.label = newlabel;
				renderList();
			});

			$('#todoListBox').on('change', '.toggle', function () {
				var completed = $(this).is(':checked');
				var label = $(this).data('label');
				var todo = todos.find(function (todo) {
					return todo.label === label;
				});
				todo.completed = completed;
				renderList();
			});

			$('#allBtn').on('click', function () {
				$('.filters a').removeClass('selected');
				$(this).addClass('selected');
				currentListType = 'all';
				renderList();
			});

			$('#activeBtn').on('click', function () {
				$('.filters a').removeClass('selected');
				$(this).addClass('selected');
				currentListType = 'active';
				renderList();
			});

			$('#completedBtn').on('click', function () {
				$('.filters a').removeClass('selected');
				$(this).addClass('selected');
				currentListType = 'completed';
				renderList();
			});

			$('.clear-completed').on('click', function () {
				todos = todos.filter(function (todo) {
					return !todo.completed;
				});
				renderList();
			});

		});
	</script>
</body>

</html>